<template>
  <el-dialog
    v-model="dialogVisible"
    :title="
      level
        ? `${optionInfo?.type === 'add' ? '添加' : '编辑'}${level === 1 ? (optionInfo?.type === 'add' ? '' : '一级') : level === 2 ? '二级' : '三级'}属性`
        : '添加属性'
    "
    width="1400"
    align-center
    @close="closeDialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form :model="form" label-width="auto" :rules="rules" style="max-width: 600px">
      <el-form-item label="关联分类" prop="classify">
        <el-tree-select
          v-model="form.classify"
          :data="optionInfo.currentClassNode"
          check-strictly
          :render-after-expand="false"
          style="width: 240px"
          node-key="categoryId"
          :props="{
            label: 'name',
            children: 'children'
          }"
        />
      </el-form-item>
      <el-form-item label="分类预览" class="classify-review" style="margin-top: 20px">
        <p>{{ optionInfo.classifyTitle }}</p>
      </el-form-item>
    </el-form>

    <div class="hr" style="margin: 20px 0"></div>
    <div class="form-list">
      <el-form v-for="(item, index) in formList" ref="formRef" :key="index" :inline="true" :model="item" class="demo-form-inline">
        <!-- 一级分类 -->
        <div class="level1" v-if="item.delFlag === 0">
          <el-row>
            <el-col :span="20">
              <el-form-item
                label="一级属性名称"
                prop="statsTitle"
                :rules="{ required: true, message: '', trigger: ['blur', 'change'] }"
              >
                <el-input
                  v-model.trim="item['statsTitle']"
                  placeholder="请输入"
                  clearable
                  maxlength="10"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                  style="width: 250px"
                  oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
                />
              </el-form-item>
              <el-form-item label="" prop="stasType" :rules="{ required: true, message: '', trigger: ['blur', 'change'] }">
                <el-select
                  v-model="item['stasType']"
                  placeholder="选择属性类型"
                  style="width: 130px"
                  :disabled="
                    (optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1) || item.quote == 1
                  "
                  @change="
                    val => {
                      setLevel(item, val);
                    }
                  "
                >
                  <el-option label="输入框" :value="1" />
                  <el-option label="单选框" :value="2" />
                  <el-option label="复选框" :value="3" />
                  <el-option label="规范数值输入" :value="4" />
                </el-select>
              </el-form-item>
              <el-form-item label="顺序号">
                <el-input
                  v-model="item['sortOrder']"
                  type="number"
                  placeholder="请输入"
                  style="width: 80px"
                  min="1"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                />
                <!-- <el-button
                  v-if="optionInfo.type === 'edit'"
                  type="primary"
                  link
                  class="add-attr"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                  @click="clickAddAttrTips(item)"
                  >添加属性说明</el-button
                > -->
              </el-form-item>
            </el-col>
            <el-col :span="4" class="del-wrap">
              <el-icon
                class="del-icon f16"
                @click="delLevel1(item, index)"
                :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
              >
                <Delete />
              </el-icon>
            </el-col>
          </el-row>
          <el-row class="mt18">
            <el-col :span="22">
              <el-form-item label="是否筛选" class="mr20">
                <el-radio-group
                  v-model="item['screen']"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                >
                  <el-radio :label="1" :value="1">是</el-radio>
                  <el-radio :label="0" :value="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="是否必填" class="mr20">
                <el-radio-group
                  v-model="item['required']"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                >
                  <el-radio :label="1" :value="1">是</el-radio>
                  <el-radio :label="0" :value="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="状态" class="mr20">
                <el-radio-group
                  v-model="item['status']"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                >
                  <el-radio :label="1" :value="1">显示</el-radio>
                  <el-radio :label="0" :value="0">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="是否显示" class="mr20">
                <el-radio-group
                  v-model="item['isViewProperty']"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                >
                  <el-radio :label="1" :value="1">显示</el-radio>
                  <el-radio :label="0" :value="0">隐藏</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="设为平台属性">
                <template #label>
                  <p>
                    设为平台属性
                    <el-popover
                      placement="top"
                      :width="300"
                      trigger="hover"
                      content="标签在供应商端选择后，在商品审核上架状态下，不支持修改，请根据业务需求进行配置，（商家自有工厂不受影响）"
                    >
                      <template #reference>
                        <el-icon><QuestionFilled /></el-icon>
                      </template>
                    </el-popover>
                  </p>
                </template>
                <el-radio-group
                  v-model="item['isPlatform']"
                  :disabled="
                    (optionInfo.type === 'add' && level !== 1) ||
                    (optionInfo.type === 'edit' && level !== 1) ||
                    !(item.stasType === 2 || item.stasType === 3) ||
                    item._isPlatformFlag
                  "
                >
                  <el-radio :label="1" :value="1">是</el-radio>
                  <el-radio :label="0" :value="0">否</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="设为搜索条件">
                <el-radio-group
                  v-model="item['isSearchCondition']"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                >
                  <el-radio :label="1" :value="1">是</el-radio>
                  <el-radio :label="0" :value="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="2" class="add-wrap">
              <el-button
                v-if="
                  (optionInfo.type === 'edit' && level === 1) ||
                  (optionInfo.type === 'add' && level === 2) ||
                  JSON.stringify(optionInfo.formData) === '{}'
                "
                :disabled="!(item.stasType === 2 || item.stasType === 3)"
                type="primary"
                size="small"
                @click="addLevel2(item, index)"
                >添加二级属性</el-button
              >
            </el-col>
          </el-row>
          <!-- 规范数值输入 -->
          <el-row>
            <el-col :span="24" v-if="item.stasType === 4" class="standard-input mt20">
              <div>
                <el-input
                  id="test"
                  v-model="item.propTemplate"
                  :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1)"
                  style="width: 100%"
                  :rows="2"
                  type="textarea"
                  placeholder="请输入"
                  @click="
                    e => {
                      handleBlur(e, index);
                    }
                  "
                  @blur="
                    e => {
                      handleBlur(e, index);
                    }
                  "
                  @keyup.delete="
                    e => {
                      handleKeyUp(e, index);
                    }
                  "
                />

                <!-- <jsxCom :str="item.textarea" /> -->
              </div>
              <div
                class="mt14 mb14"
                style="display: flex; justify-content: space-between"
                v-if="!((optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level !== 1))"
              >
                <div>
                  <el-button type="primary" link @click="getEmo(index, '【数值】')" class="f12">
                    <img class="mr10" src="@/assets/images/insert-icon.png" alt="" style="width: 16px; height: 16px" />插入数值
                  </el-button>
                  <el-button type="primary" link @click="getEmo(index, '【字符】')" class="f12">
                    <img class="mr10" src="@/assets/images/insert-icon.png" alt="" style="width: 16px; height: 16px" />插入字符
                  </el-button>
                </div>
                <el-button type="primary" link class="f12" @click="clickView(item)" :disabled="!item.propTemplate">
                  <img class="mr10" src="@/assets/images/eyes-icon.png" alt="" style="width: 16px; height: 16px" />预览
                </el-button>
              </div>
            </el-col>
          </el-row>
          <div class="hr" v-if="item.children.length > 0"></div>
        </div>

        <!-- 二级分类 -->
        <div class="level2" v-for="(item2, index2) in item.children" :key="index2">
          <div class="level2-item" v-if="item.delFlag === 0 && item2.delFlag === 0">
            <el-row>
              <el-col :span="24">
                <el-form-item
                  label="二级属性名称"
                  :prop="`children.${index2}.statsTitle`"
                  :rules="{ required: true, message: '', trigger: ['blur', 'change'] }"
                >
                  <el-input
                    v-model.trim="item2['statsTitle']"
                    placeholder="请输入"
                    clearable
                    maxlength="10"
                    :disabled="level === 3"
                    style="width: 250px"
                    oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
                  />
                </el-form-item>
                <el-form-item
                  label=""
                  :prop="`children.${index2}.stasType`"
                  :rules="{ required: true, message: '', trigger: ['blur', 'change'] }"
                >
                  <el-select
                    v-model="item2['stasType']"
                    placeholder="选择属性类型"
                    style="width: 130px"
                    :disabled="level === 3 || item2.quote === 1"
                    @change="
                      val => {
                        setLevel(item2, val);
                      }
                    "
                  >
                    <el-option label="输入框" :value="1" />
                    <el-option label="单选框" :value="2" />
                    <el-option label="复选框" :value="3" />
                    <el-option label="规范数值输入" :value="4" />
                  </el-select>
                </el-form-item>
                <el-form-item label="顺序号">
                  <el-input
                    v-model="item2['sortOrder']"
                    type="number"
                    placeholder="请输入"
                    style="width: 80px"
                    min="1"
                    :disabled="level === 3"
                  />
                  <el-button
                    v-if="optionInfo.type === 'edit' && item2?.stastsId"
                    type="primary"
                    link
                    class="add-attr"
                    :disabled="(optionInfo.type === 'add' && level !== 1) || (optionInfo.type === 'edit' && level === 3)"
                    @click="clickAddAttrTips(item2)"
                    >添加属性说明</el-button
                  >
                  <p class="f16 ml20">
                    <el-icon class="del-icon" @click="delLevel2(item, index2)"><Delete /></el-icon>
                  </p>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="mt18">
              <el-col :span="20">
                <el-form-item label="是否筛选" class="mr40" style="margin-left: 100px">
                  <el-radio-group v-model="item2['screen']" :disabled="level === 3">
                    <el-radio :label="1" :value="1">是</el-radio>
                    <el-radio :label="0" :value="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="是否必填" class="mr40">
                  <el-radio-group v-model="item2['required']" :disabled="level === 3">
                    <el-radio :label="1" :value="1">是</el-radio>
                    <el-radio :label="0" :value="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="状态" class="mr40">
                  <el-radio-group v-model="item2['status']" :disabled="level === 3">
                    <el-radio :label="1" :value="1">显示</el-radio>
                    <el-radio :label="0" :value="0">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="是否显示">
                  <el-radio-group v-model="item2['isViewProperty']" :disabled="level === 3">
                    <el-radio :label="1" :value="1">显示</el-radio>
                    <el-radio :label="0" :value="0">隐藏</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 规范数值输入 -->
            <el-row>
              <el-col :span="24" v-if="item2.stasType === 4" class="standard-input mt20">
                <div>
                  <el-input
                    v-model="item2.propTemplate"
                    :disabled="level === 3"
                    style="width: 100%"
                    :rows="2"
                    type="textarea"
                    placeholder="请输入"
                    @click="
                      e => {
                        handleBlur(e, index2, index);
                      }
                    "
                    @blur="
                      e => {
                        handleBlur(e, index2, index);
                      }
                    "
                    @keyup.delete="
                      e => {
                        handleKeyUp(e, index2, index);
                      }
                    "
                  />

                  <!-- <jsxCom :str="item2.textarea" /> -->
                </div>
                <div class="mt14 mb14" style="display: flex; justify-content: space-between" v-if="!(level === 3)">
                  <div>
                    <el-button type="primary" link @click="getEmo(index2, '【数值】', index)" class="f12">
                      <img class="mr10" src="@/assets/images/insert-icon.png" alt="" style="width: 16px; height: 16px" />插入数值
                    </el-button>
                    <el-button type="primary" link @click="getEmo(index2, '【字符】', index)" class="f12">
                      <img class="mr10" src="@/assets/images/insert-icon.png" alt="" style="width: 16px; height: 16px" />插入字符
                    </el-button>
                  </div>
                  <el-button type="primary" link class="f12" @click="clickView(item2)" :disabled="!item2.propTemplate">
                    <img class="mr10" src="@/assets/images/eyes-icon.png" alt="" style="width: 16px; height: 16px" />预览
                  </el-button>
                </div>
              </el-col>
            </el-row>

            <!-- 三级分类 -->
            <el-row class="pl25 mt20">
              <el-col :span="20" :offset="2" class="level3">
                <template v-for="(item3, index3) in item2.children" :key="index3">
                  <el-form-item
                    label="三级属性名称"
                    v-if="item3.delFlag === 0"
                    :prop="`children.${index2}.children.${index3}.statsTitle`"
                    :rules="{ required: true, message: '', trigger: ['blur', 'change'] }"
                  >
                    <div style="display: flex; align-items: center">
                      <el-input
                        v-model.trim="item3['statsTitle']"
                        placeholder="请输入"
                        clearable
                        maxlength="10"
                        style="width: 250px"
                        oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
                      />
                      <el-button
                        v-if="optionInfo.type === 'edit' && item3?.stastsId"
                        type="primary"
                        link
                        class="add-attr"
                        @click="clickAddAttrTips(item3)"
                        >添加属性说明</el-button
                      >
                      <p class="f16 ml20">
                        <el-icon class="del-icon" @click="delLevel3(item2, index3, item)"><Delete /></el-icon>
                      </p>
                    </div>
                  </el-form-item>
                </template>
              </el-col>
            </el-row>
            <el-row class="pl25">
              <el-col :span="20" :offset="2">
                <el-button
                  v-if="!(optionInfo.type === 'edit' && level === 3)"
                  :disabled="!(item2.stasType === 2 || item2.stasType === 3)"
                  @click="addLevel3(item2, index2, item)"
                  type="primary"
                  link
                  :icon="CirclePlusFilled"
                  class="add-item"
                  >添加三级属性</el-button
                >
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
      <el-button
        v-if="JSON.stringify(optionInfo.formData) === '{}'"
        @click="addLevel1"
        type="primary"
        link
        :icon="CirclePlusFilled"
        class="add-item add-item1"
      >
        添加一级属性
      </el-button>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 插入数值、字符预览 -->
  <el-dialog v-model="dialogVisibleNS" align-center title="预览" width="810" :before-close="handleCloseNS">
    <jsxCom :str="viewCurrObj.propTemplate" />
  </el-dialog>

  <!-- 富文本编辑器 -->
  <el-dialog
    v-model="dialogEditorVisible"
    title="属性标签说明"
    width="800"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="'default'"
        :key="selectedContent"
      />
      <Editor
        :key="selectedContent"
        style="height: 500px; overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="'simple'"
        @onCreated="handleCreated"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeEditorDialog">取消</el-button>
        <el-button type="primary" @click="submitEditor">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, shallowRef, onBeforeUnmount, computed } from "vue";
import { Delete, CirclePlusFilled, QuestionFilled } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { getRichText, saveSassRichText } from "@/api/products/attribute";
import { getFolder, updateTreeValue, replaceNS } from "@/utils/index";
import jsxCom from "@/views/products/specifications/components/jsxCom.vue";

const emit = defineEmits(["close", "submit"]);
const props = defineProps({
  optionInfo: {
    type: Object,
    default: () => {
      return {
        isShow: false,
        type: "add", //add edit
        formData: {},
        list: [],
        currentClassNode: [], //当前分类tree
        classifyTitle: "" //分类预览
      };
    }
  }
});

watch(
  () => props.optionInfo,
  val => {
    dialogVisible.value = val.isShow;
    level.value = val?.formData?.fomart ? val?.formData?.fomart.split("-").length : 0;
    val.currentClassNode.children = []; //回显商品分类下拉数据
    form.value.classify = val.currentClassNode[0].categoryId; //回显商品分类下拉数据
    console.log("传到子组件的数据", val);
    const DATA = JSON.parse(JSON.stringify(val.formData));
    if (val.type === "add") {
      level.value = level.value + 1;
      formList.value = [
        {
          children: [],
          required: 1,
          status: 1,
          isViewProperty: 1,
          isPlatform: 0,
          isSearchCondition: 0,
          _isPlatformFlag: false,
          delFlag: 0,
          sortOrder: 1,
          screen: 1
        }
      ]; //添加时，清空表单数据
      addReview(DATA); //新增时，回显数据
    } else {
      editReview(DATA); //编辑时，回显数据
    }
  },
  {
    deep: true
  }
);

const form = ref({});
const rules = ref({
  classify: [{ required: true, message: "Please input Activity name", trigger: ["change", "blur"] }]
});
const level = ref(0);
const dialogEditorVisible = ref(false); //富文本编辑框
const dialogVisible = ref(false);
const formList = ref([
  {
    children: [],
    required: 1,
    status: 1,
    isViewProperty: 1,
    isPlatform: 0,
    isSearchCondition: 0,
    _isPlatformFlag: false,
    delFlag: 0,
    sortOrder: 1,
    screen: 1
  }
]);
const formRef = ref();
const dialogVisibleNS = ref(false); //插入数值、字符 预览弹窗
const viewCurrObj = ref({});

// ===============================插入数值、字符==========================================================

const clickView = item => {
  dialogVisibleNS.value = true;
  setTimeout(() => {
    viewCurrObj.value = item;
  }, 50);
};

const handleCloseNS = () => {
  dialogVisibleNS.value = false;
};
const handleKeyUp = (e, index, pindex) => {
  if (pindex || pindex === 0) {
    // 二级
    if (isDel4.value) {
      formList.value[pindex].children[index].propTemplate = `${delStrStart.value}${delStrEnd.value}`;
    }
  } else {
    // 一级
    if (isDel4.value) {
      formList.value[index].propTemplate = `${delStrStart.value}${delStrEnd.value}`;
    }
  }
};
const cursorPos = ref(0); // 光标位置
const delStrStart = ref(""); // 删除字符开始的位置
const delStrEnd = ref(""); // 删除字符结束的位置
const isDel4 = ref(false);
const handleBlur = (e, index, pindex) => {
  cursorPos.value = e.srcElement.selectionStart;
  console.log("光标位置===", cursorPos.value);

  if (cursorPos.value >= 4) {
    if (pindex || pindex === 0) {
      // 二级
      delStrStart.value = formList.value[pindex]?.children[index].propTemplate.substring(0, cursorPos.value - 4);
      delStrEnd.value = formList.value[pindex]?.children[index].propTemplate.substring(cursorPos.value);
      if (formList.value[pindex]?.children[index].propTemplate[cursorPos.value - 1] === "】") {
        isDel4.value = true;
      } else {
        isDel4.value = false;
      }
    } else {
      // 一级
      delStrStart.value = formList.value[index].propTemplate.substring(0, cursorPos.value - 4);
      delStrEnd.value = formList.value[index].propTemplate.substring(cursorPos.value);
      if (formList.value[index].propTemplate[cursorPos.value - 1] === "】") {
        isDel4.value = true;
      } else {
        isDel4.value = false;
      }
    }

    console.log("del===========", isDel4.value, delStrStart.value, "-", delStrEnd.value);
  } else {
    isDel4.value = false;
    delStrStart.value = "";
    delStrEnd.value = "";
  }
};

const getEmo = (index, str, pindex) => {
  if (pindex || pindex === 0) {
    if (!formList.value[pindex]?.children[index]?.propTemplate) {
      formList.value[pindex].children[index].propTemplate = str;
      console.log(111, formList.value);
    } else {
      const start = formList.value[pindex]?.children[index].propTemplate.substring(0, cursorPos.value);
      const end = formList.value[pindex]?.children[index].propTemplate.substring(cursorPos.value);
      // console.log("aaaaaaaaaaa", start, end);
      formList.value[pindex].children[index].propTemplate = `${start}${str}${end}`;
      console.log(222, formList.value);
    }
  } else {
    if (!formList.value[index].propTemplate) {
      formList.value[index].propTemplate = str;
    } else {
      const start = formList.value[index].propTemplate.substring(0, cursorPos.value);
      const end = formList.value[index].propTemplate.substring(cursorPos.value);
      // console.log("aaaaaaaaaaa", start, end);
      formList.value[index].propTemplate = `${start}${str}${end}`;
    }
  }
};

// =========================================================================================

const setLevel = (item, val) => {
  if (val === 1 || val === 4) {
    //输入框的时候
    updateTreeValue(item.children, "delFlag", 1);

    //如果时输入框且平台属性为true，那么重置平台属性为false
    if (item.isPlatform === 1) {
      item.isPlatform = 0;
    }
  } else {
    updateTreeValue(item.children, "delFlag", 0);
  }
};

const addReview = formData => {
  if (JSON.stringify(formData) === "{}") return;
  const parentsArr = orgChildIdFindParent(formData.stastsId, props.optionInfo.list);
  let _formData = JSON.parse(JSON.stringify(formData));
  _formData.children = [];
  /** %f转成【数值】 %s转成【字符】*/
  if (_formData.propTemplate) _formData.propTemplate = replaceNS(_formData.propTemplate, -1);
  _formData.children.map(item2 => {
    if (item2.propTemplate) item2.propTemplate = replaceNS(item2.propTemplate, -1);
  });
  if (level.value === 2) {
    formList.value = [_formData];
    // console.log("添加，渲染二级===", formList.value, formData);
  } else if (level.value === 3) {
    formList.value = [
      {
        ...parentsArr[0],
        children: [_formData]
      }
    ];
    // console.log("添加，渲染三级===", formList.value, formData);
  }
};

const editReview = formData => {
  if (JSON.stringify(formData) === "{}") return;
  const parentsArr = orgChildIdFindParent(formData.stastsId, props.optionInfo.list);
  let _formData = JSON.parse(JSON.stringify(formData));
  // _formData.children = [];
  /** %f转成【数值】 %s转成【字符】*/
  if (_formData.propTemplate) _formData.propTemplate = replaceNS(_formData.propTemplate, -1);
  _formData.children.map(item2 => {
    if (item2.propTemplate) item2.propTemplate = replaceNS(item2.propTemplate, -1);
  });
  if (level.value === 1) {
    formList.value = [_formData];
    // console.log("添加，渲染一级===", formList.value, formData);
  } else if (level.value === 2) {
    formList.value = [
      {
        ...parentsArr[0],
        children: [_formData]
      }
    ];
    // console.log("添加，渲染二级===", formList.value, formData);
  } else if (level.value === 3) {
    let _formData3 = parentsArr[1];
    _formData3.children = [_formData];
    formList.value = [
      {
        ...parentsArr[0],
        children: [_formData3]
      }
    ];
    // console.log("添加，渲染三级===", formList.value, formData);
  }

  formList.value[0]._isPlatformFlag = false;
  _formData?.children?.map(obj2 => {
    const arr3 = obj2.children.filter(obj3 => obj3.delFlag === 0);
    if (arr3.length > 0) {
      formList.value[0]._isPlatformFlag = true;
    }
  });
};

const closeDialog = async () => {
  //   resetForm(); //清空表单
  const refs = formRef.value;
  for (let item of refs) {
    await item.resetFields();
  }
  formList.value = [
    {
      children: [],
      required: 1,
      status: 1,
      isViewProperty: 1,
      isPlatform: 0,
      isSearchCondition: 0,
      _isPlatformFlag: false,
      delFlag: 0,
      sortOrder: 1,
      screen: 1
    }
  ];
  emit("close");
};
const submit = async () => {
  console.log("formList表单数据===", formList.value);
  const DATA = JSON.parse(JSON.stringify(formList.value));
  const data1 = renameChildKey(DATA, "level2", "children");
  const data2 = renameChildKey(data1, "level3", "children");
  await validateFun(); //多表单校验
  if (isValidate.value) {
    // 多表单校验通过
    data2.map(item => {
      if (item.propTemplate) item.propTemplate = replaceNS(item.propTemplate, 1);
      item.children.map(item2 => {
        if (item2.propTemplate) item2.propTemplate = replaceNS(item2.propTemplate, 1);
      });
    });
    emit("submit", data2, props.optionInfo.type, level.value);
  }
};

//多表单校验
const isValidate = ref(true); //表单是否校验通过
const validateFun = async () => {
  const refs = formRef.value;
  isValidate.value = true;
  for (let item of refs) {
    await item.validate((valid, fields) => {
      if (valid) {
        isValidate.value = true;
        console.log("submit!");
      } else {
        isValidate.value = false;
        console.log("error submit!", fields);
      }
    });
  }
};

const addLevel1 = () => {
  formList.value.push({
    children: [],
    required: 1,
    status: 1,
    isViewProperty: 1,
    isPlatform: 0,
    isSearchCondition: 0,
    _isPlatformFlag: false,
    delFlag: 0,
    sortOrder: 1,
    screen: 1
  });
};
const addLevel2 = (item, index) => {
  item.children.push({
    children: [],
    delFlag: 0,
    required: 1,
    status: 1,
    isViewProperty: 1,
    sortOrder: 1,
    screen: 1
  });
};
const addLevel3 = (item2, index2, item) => {
  console.log("添加三级属性", item2);
  item2.children.push({ delFlag: 0 });

  //如果一级属性的平台属性为true，那么重置平台属性为false
  if (item.isPlatform === 1) {
    item.isPlatform = 0;
  }
  item._isPlatformFlag = true;
};

const delLevel1 = (item, index) => {
  // if (formList.value.length <= 1) return ElMessage.error("至少保留一条数据");
  if (props.optionInfo.type === "edit") {
    console.log("编辑的时候，删除操作特殊处理");
    item.delFlag = 1; //只有delFlag=1的数据，后台数据库才会进行删除
  } else {
    formList.value.splice(index, 1);
  }
};
const delLevel2 = (item, index) => {
  // if (item.children.length <= 1) return ElMessage.error("至少保留一条数据");
  if (props.optionInfo.type === "edit") {
    console.log("编辑的时候，删除操作特殊处理");
    item.children[index].delFlag = 1; //只有delFlag=1的数据，后台数据库才会进行删除
  } else {
    item.children.splice(index, 1);
  }

  item._isPlatformFlag = false;
  item.children
    .filter(obj2 => obj2.delFlag === 0)
    ?.map(obj2 => {
      const arr3 = obj2.children.filter(obj3 => obj3.delFlag === 0);
      if (arr3.length > 0) {
        item._isPlatformFlag = true;
      }
    });
};
const delLevel3 = (item2, index3, item) => {
  // if (item.children.length <= 1) return ElMessage.error("至少保留一条数据");
  if (props.optionInfo.type === "edit") {
    console.log("编辑的时候，删除操作特殊处理");
    item2.children[index3].delFlag = 1; //只有delFlag=1的数据，后台数据库才会进行删除
  } else {
    item2.children.splice(index3, 1);
  }

  item._isPlatformFlag = false;
  item.children?.map(obj2 => {
    const arr3 = obj2.children.filter(obj3 => obj3.delFlag === 0);
    if (arr3.length > 0) {
      item._isPlatformFlag = true;
    }
  });
};
const renameChildKey = (tree, orign_childKey, new_childKey) => {
  tree.forEach(item => {
    if (item[orign_childKey]) {
      item[new_childKey] = item[orign_childKey];
      delete item[orign_childKey];
    }
    if (item[new_childKey] && item[new_childKey].length > 0) {
      renameChildKey(item[new_childKey], orign_childKey, new_childKey);
    }
  });
  return tree;
};

// 根据子id找父,返回值不包含查找的节点
const findParentsId = (treeData, id) => {
  if (treeData.length == 0) return;
  for (let i = 0; i < treeData.length; i++) {
    if (treeData[i].stastsId == id) {
      return [];
    } else {
      if (treeData[i].children) {
        let res = findParentsId(treeData[i].children, id);
        if (res !== undefined) {
          return res.concat({ ...treeData[i] }).reverse();
        }
      }
    }
  }
};
// 组织结构子id，找父
const orgChildIdFindParent = (childId, orgList = []) => {
  const result = findParentsId(orgList, childId);
  return result || [];
};

//====================================富文本编辑器========================================================================================
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("");
const toolbarConfig = {};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      customUpload: async (file, insertFn) => {
        // console.log("触发图片上传");
        await handleAvatarChangeIcon(file);
        // console.log("上传图片的地址===", imgUrl.value);
        insertFn(imgUrl.value.split("?")[0]); // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
      }
    },
    uploadVideo: {
      customUpload: async (file, insertFn) => {
        // console.log("触发视频上传");
        await handleAvatarChangeIcon(file, "video");
        console.log("上传视频的地址===", videoUrl.value);
        insertFn(videoUrl.value.split("?")[0]); // 最后插入视频 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
      }
    }
  }
};
const currentObj = ref({}); //当前点击的对象，用于富文本编辑器值的赋值
const imgUrl = ref(""); //编辑器每选择一次图片，上传后的地址
const videoUrl = ref(""); //编辑器每选择一次视频，上传后的地址

//为富文本编辑器添加key值，解决编辑成功后又重新打开时报错的问题
const selectedContent = computed(() => {
  return String(new Date().getTime()) + dialogEditorVisible.value;
});

//打开属性说明 富文本编辑器
const clickAddAttrTips = async item => {
  currentObj.value = item;
  //   console.log("属性说明富文本框，节点信息===", item);
  valueHtml.value = "";
  const params = {
    sourceType: 1,
    sourceId: item.stastsId
  };
  const _html = ref("");
  await getRichText(params).then(res => {
    if (res.code === 200) {
      _html.value = res.data.content;
      // _html.value =
      //   "<p>123123</p><p><img src=\"http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/default.png\" alt=\"\" data-href=\"\" style=\"\"/></p>";
      // "<p>123123</p><p><img src=\"http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/default.png?OSSAccessKeyId=STS.NV1WaBwKBTjqKq4XB3w4NMpEh&Expires=1714444659&Signature=CNmKQ7hf7VGvCnEGQKPf%2BynUjAo%3D&security-token=CAIS0QJ1q6Ft5B2yfSjIr5WEHNv2mpRj46iaSVeFvEJme7tiorXuijz2IHhMfHRhAuAcsPg%2FmW9S7Pkflrp0UIQAWlbFccY19Jle%2FUa7ZI7M4y4ZZjOe0c%2FLI3OaLjKm9u2wCryLYbGwU%2FOpbE%2B%2B5U0X6LDmdDKkckW4OJmS8%2FBOZcgWWQ%2FKBlgvRq0hRG1YpdQdKGHaONu0LxfumRCwNkdzvRdmgm4NgsbWgO%2Fks0WH3Qyim7FM9t%2BqesH1MPMBZskvD42Hu8VtbbfE3SJq7BxHybx7lqQs%2B02c5onFXggKs0%2FYb7qJrYc1c1JjHa8hAOtbtvngmLhit%2BXf0p7wzxtdwFCi9LYwq%2BtKqeqz%2B4PBXr5RHd6TsPTfZEYLzVCNrBnSZ1wRAhF3Vczg1hMf8uTUs9g3y15%2BGZkju8rSM9l0oONukUNtljWxrYLhT391iQTHuU5wGoABb48h17pOu6bd4Eb1CLYJ5gFclYbTpPUYfLgX68hcyNCfey2dUJviKaWtaLlUNWelqBIYZArumYjsd0AyCkDnLgV5wCYzqzVnTKYYIeZ8vYxs6bD3siYQ7ujRVtEWagB1mE5KJq%2Bam9cjvyUa9YIO%2BG1PLDWMKRzTQ8csu2VRJicgAA%3D%3D\" alt=\"\" data-href=\"\" style=\"\"/></p>";
    }
  });
  console.log("富文本编辑器内容===", _html.value);
  valueHtml.value = _html.value;
  dialogEditorVisible.value = true;
};
const closeEditorDialog = () => {
  dialogEditorVisible.value = false;
  valueHtml.value = "";
};
//保存富文本编辑器内容
const submitEditor = () => {
  const params = {
    sourceType: 1,
    sourceId: currentObj.value.stastsId,
    content: valueHtml.value
  };
  console.log("这是保存富文本的信息===", params);
  saveSassRichText(params).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "属性说明编辑成功",
        type: "success"
      });
      dialogEditorVisible.value = false;
      valueHtml.value = "";
    }
  });
};

const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

//====================================文件上传========================================================================================

import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();

const handleAvatarChangeIcon = async (file, type = "img") => {
  //选中文件触发的change事件
  // console.log(file);
  await customUpload({ file }, type);
};

/**
 * 上传
 */
const customUpload = async (option, type) => {
  const folder = getFolder();
  // const objName = folder + option.file.name;
  const objName = folder + option.file.name.split(".")[0] + new Date().getTime() + "." + option.file.name.split(".")[1];

  await ossStore
    .submit(objName, option.file)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl);
      if (type === "img") {
        imgUrl.value = res.fileUrl.split("?")[0];
      } else {
        videoUrl.value = res.fileUrl.split("?")[0];
      }
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
</script>

<style lang="scss" scoped>
:deep(.el-form-item.is-required:not(.is-no-asterisk).asterisk-left > .el-form-item__label:before) {
  display: none;
}
:deep(.classify-review) {
  height: 22px;
  line-height: 22px;
  .el-form-item__label,
  .el-form-item__content p {
    height: 22px;
    line-height: 22px;
  }
}
:deep(.w-e-textarea-video-container) {
  video {
    width: 100%;
  }
}
:deep(.w-e-text-container) {
  .w-e-scroll {
    height: 600px;
  }
}
p {
  margin: 0;
}
i {
  vertical-align: middle;
}
.hr {
  border-top: 1px solid #dcdfe6;
  margin: 0 -16px;
  margin-top: 20px;
}
.el-form--inline .el-form-item {
  margin-right: 10px;
}
.el-form-item {
  margin-bottom: 0;
}
.del-icon {
  cursor: pointer;
}
.add-attr {
  margin-left: 20px;
  font-size: 12px;
}
.add-item {
  font-size: 12px;
  &.add-item1 {
    margin-top: 10px;
  }
}
.del-wrap,
.add-wrap {
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.form-list {
  .el-form {
    &:not(:last-of-type) {
      margin-bottom: 20px;
    }
    .el-radio {
      margin-right: 10px;
    }
    .el-radio {
      margin-right: 10px;
    }
  }
}
.level1 {
  background-color: #f5f7fa;
  padding: 20px 16px;
}
.level2 {
  background-color: #f5f7fa;
  padding: 0px 16px;
  & > .level2-item {
    padding: 20px 0px;
  }
}
.level2 {
  padding-top: 0;
}
.level3 {
  display: flex;
  flex-direction: column;
  .el-form-item {
    margin-bottom: 10px;
  }
}
</style>
